#include "DbPart.h"
#include "connectpool.h"
#include <sstream>
#include <vector>
#include "Game.h"

CDbPart::CDbPart():m_dbHandler(NULL)
{
}

CDbPart::~CDbPart()
{
}

stUserinfo* CDbPart::getUserinfoByGame(const unsigned int uid, const int game_id)
{
	ostringstream ossSQL;
	ossSQL << "select userinfo from game_userinfo_" << uid % MOD_DENOMINATOR << " where uid =" << uid  << " and game_id = " << game_id;

	if (m_dbHandler->m_pMysqlConn->GetConnect() == NULL)
		{
		m_dbHandler->m_strError = m_dbHandler->m_pMysqlConn->What();
		log_error("getUserinfo Error: %s\r Sql=%s \n", m_dbHandler->m_pMysqlConn->What().c_str(), ossSQL.str().c_str());

		return nullptr;
	}
	if (m_dbHandler->m_pStore->Query(ossSQL.str()))
	{
		unsigned long count = m_dbHandler->m_pStore->RowCount();
		if (count == 0)
		{
			log_error("ERROR getUserinfo uid=%d count=0", uid);

			return nullptr;
		}

		std::string userinfo = m_dbHandler->m_pStore->GetItemString(0, "userinfo");
		game_userinfo::userinfoDataDb data;
		data.ParseFromString(userinfo);

		stUserinfo* pUserInfo = new stUserinfo();
		for (int i = 0; i < data.field_value_list_size(); i++)
		{
			game_userinfo::USER_FIELD field = data.field_value_list(i).field();
			if (field == game_userinfo::FIELD_HEADER)
			{
				pUserInfo->header = data.field_value_list(i).str_val();
			}
			else if (field == game_userinfo::FIELD_NICKNAME)
			{
				pUserInfo->nickname = data.field_value_list(i).str_val();
			}
			else if (field == game_userinfo::FIELD_GENDER)
			{
				pUserInfo->gender = data.field_value_list(i).int_val();
			}
		}

		log_debug("getUserinfo from db SQL=%s, count=%d uid=%u game_id=%d, gender=%d, header=%s, nickname=%s",
			ossSQL.str().c_str(), (int)count, uid, (int)game_id, pUserInfo->gender, pUserInfo->header.c_str(), pUserInfo->nickname.c_str());

		return pUserInfo;
	}

	return nullptr;
}

// bool CDbPart::addUser(const unsigned int uid, int game_id, stUserinfo* pUserInfo)
// {
// 	if (0 == uid)
// 		return false;
// 	game_userinfo::userinfoDataDb data;
// 	data.set_gender(pUserInfo->gender);
// 	data.set_header(pUserInfo->header);
// 	data.set_nickname(pUserInfo->nickname);
//     std::string info;
// 	data.SerializeToString(&info);

// 	ostringstream ossSQL;

// 	ossSQL << "insert into game_userinfo_" << uid % MOD_DENOMINATOR << "(uid, game_id, userinfo) values(" << uid << ", "<<game_id <<", "<<info << ")";

	
// 	log_debug("sql = %s", ossSQL.str().c_str());

// 	if (m_dbHandler->m_pMysqlConn->GetConnect() == NULL)
// 	{
// 		m_dbHandler->m_strError = m_dbHandler->m_pMysqlConn->What();
// 		log_error("getUserinfo Error: %s\r Sql=%s \n", m_dbHandler->m_pMysqlConn->What().c_str(), ossSQL.str().c_str());

// 		return false;
// 	}

// 	return m_dbHandler->UpdateSql(ossSQL.str().c_str());
// }